package es.jclm.agri.foragri.dao.impl;

import java.io.Serializable;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import es.jclm.agri.foragri.commons.dao.impl.GenericJpaDao;
import es.jclm.agri.foragri.dao.EmpleadoDao;
import es.jclm.agri.foragri.dao.UserDao;
import es.jclm.agri.foragri.model.Empleado;
import es.jclm.agri.foragri.model.SearchCriteria;
import es.jclm.agri.foragri.model.UserEntity;

/**
 * Data access object JPA impl to work with User entity database operations.
 * 
 * @author generoso.almaraz
 */
@Component("empleadoJpaDao")
public class EmpleadoJpaDao extends GenericJpaDao<Empleado, Long> implements EmpleadoDao, Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected EmpleadoJpaDao() {
		super(Empleado.class);
	}
	
	@Transactional(readOnly = true)
	public int getNumberOfEmpleados(SearchCriteria criteria) {
		String pattern = getSearchPattern(criteria);
		Long count = (Long) getEntityManager()
				.createQuery(
						"select count(h.id) from Hotel h where lower(h.name) like :pattern or lower(h.city) like :pattern "
								+ "or lower(h.zip) like :pattern or lower(h.address) like :pattern")
								.setParameter("pattern", pattern).getSingleResult();
		return count.intValue();
	}

	private String getSearchPattern(SearchCriteria criteria) {
		if (StringUtils.hasText(criteria.getSearchString())) {
			return "%" + criteria.getSearchString().toLowerCase().replace('*', '%') + "%";
		} else {
			return "%";
		}
	}

	private Empleado findUser(String username) {
		return (Empleado) getEntityManager().createQuery("select u from Empleado u where u.username = :username")
				.setParameter("username", username).getSingleResult();
	}

}
